#include "serial.h"
#include <QDebug>

Serial::Serial()
{
    foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) {
        serialPortList.append(info.portName());
    }
}

Serial::~Serial()
{
    if (comPort != Q_NULLPTR) {
        comPort->close();
        delete comPort;
        comPort = Q_NULLPTR;
    }
}

void Serial::portOpen()
{
    if (comPort == Q_NULLPTR) {
        return;
    }

    if (comPort->open(QIODevice::ReadWrite) || comPort->isOpen()) {
        comPort->setBaudRate(baudRate);
        switch (dataBit) {
            case 5 : comPort->setDataBits(QSerialPort::Data5); break;
            case 6 : comPort->setDataBits(QSerialPort::Data6); break;
            case 7 : comPort->setDataBits(QSerialPort::Data7); break;
            case 8 : comPort->setDataBits(QSerialPort::Data8); break;
            default : break;
        }

        switch (checkBit) {
            case 0 : comPort->setParity(QSerialPort::NoParity); break;
            case 1 : comPort->setParity(QSerialPort::EvenParity); break;
            case 2 : comPort->setParity(QSerialPort::OddParity); break;
            default : break;
        }

        switch (stopBit) {
            case 0 : comPort->setStopBits(QSerialPort::OneStop); break;
            case 1 : comPort->setStopBits(QSerialPort::OneAndHalfStop); break;
            case 2 : comPort->setStopBits(QSerialPort::TwoStop); break;
            default : break;
        }

        isSerialOpened = true;
        connect(comPort, SIGNAL(readyRead()), this, SLOT(readSerial()), Qt::QueuedConnection);
    } else {
        portClose();
        isSerialOpened = false;
    }
}

void Serial::portClose()
{
    comPort->close();

    isSerialOpened = false;
}

void Serial::changeTo(QString portName)
{
    if (comPort != Q_NULLPTR) {
        comPort->close();
        delete comPort;
        comPort = Q_NULLPTR;
    }
    comPort = new QSerialPort(portName);

    if (isSerialOpened) {
        portOpen();
    }
}

void Serial::readSerial(void)
{
    QByteArray readBuf;

    readBuf = comPort->readAll();
    if (!readBuf.isEmpty()) {
        comData.append(readBuf);

        emit readDone();
    }
}
